package com.uchiha.nova.core.tool.util;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Nullable;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author 周林静
 * @Date 2023-01-08,0008 21:56
 * @Version 1.0
 */
@Component
public class CacheExpireUtil{


    private static RedisTemplate redisTemplate;


    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        CacheExpireUtil.redisTemplate = redisTemplate;
    }

    public static  <T> T get(String preKey, String key, Callable<T> valueLoader, @Nullable Long expire) {
        if (Func.hasEmpty(preKey, key)) {
            return null;
        }
        if(redisTemplate.hasKey(preKey+key)){
            return (T) redisTemplate.opsForValue().get(preKey+key);
        }else{
            try {
                T call = valueLoader.call();

                if(ObjectUtil.isEmpty(expire)){
                    expire = 3600L;
                }
                redisTemplate.opsForValue().set(preKey+key,call,expire, TimeUnit.SECONDS);
                return call;
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }
    }


    public static void clear(String cacheName) {
        redisTemplate.delete(cacheName);
    }
}
